package cn.xtcode.service.impl;

import cn.xtcode.domain.vo.WeixinTemplateMessageVO;
import cn.xtcode.domain.req.WeixinQrCodeReq;
import cn.xtcode.domain.res.WeixinQrCodeRes;
import cn.xtcode.domain.res.WeixinTokenRes;
import cn.xtcode.service.ILoginService;
import cn.xtcode.service.weixin.IWeixinApiService;
import com.google.common.cache.Cache;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import retrofit2.Call;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: xt-code
 * @date: 2025/8/4 22:54
 * @description:
 */
@Service
public class WeixinLoginServiceImpl implements ILoginService {
    @Value("${weixin.config.app-id}")
    private String appId;

    @Value("${weixin.config.app-secreat}")
    private String appSecret;

    @Value("${weixin.config.grant-type}")

    private String grantType;

    @Value("${weixin.config.template-id}")
    private String templateId;
    @Resource
    private IWeixinApiService weixinApiService;

    @Resource
    private Cache<String, String> weixinAccessToken;

    @Resource
    private Cache<String,String> openidToken;

    @Override
    public String createQrCodeTicket() throws Exception{
        //1.获取access_token
        String accessToken = weixinAccessToken.getIfPresent(appId);

        if(accessToken == null){
            Call<WeixinTokenRes> call = weixinApiService.getToken(grantType, appId, appSecret);
            WeixinTokenRes weixinTokenRes = call.execute().body();
            //TODO 公司里，这里是判断是否为空，为空就抛出异常。
            if(weixinTokenRes == null){
                throw new RuntimeException("出现异常啦");
            }

            accessToken = weixinTokenRes.getAccess_token();

            //2.存储accessToken,使用本地缓存，可以使用redis
            weixinAccessToken.put(appId, accessToken);
        }


        // 3. 生成 ticket
        WeixinQrCodeReq weixinQrCodeReq = WeixinQrCodeReq.builder()
                .expire_seconds(2592000)
                .action_name(WeixinQrCodeReq.ActionNameTypeVO.QR_SCENE.getCode())
                .action_info(WeixinQrCodeReq.ActionInfo.builder()
                        .scene(WeixinQrCodeReq.ActionInfo.Scene.builder()
                                .scene_id(100601)
                                .build())
                        .build())
                .build();
        Call<WeixinQrCodeRes> weixinQrCodeResCall = weixinApiService.createQrCode(accessToken, weixinQrCodeReq);
        WeixinQrCodeRes weixinQrCodeRes = weixinQrCodeResCall.execute().body();
        if (null == weixinQrCodeRes){
            throw new RuntimeException("运行时异常");
        }
        return weixinQrCodeRes.getTicket();
    }

    @Override
    public void saveLoginState(String ticket, String openId) throws Exception{
        openidToken.put(ticket, openId);

        // 1. 获取 accessToken 【实际业务场景，按需处理下异常】
        String accessToken = weixinAccessToken.getIfPresent(appId);
        if (null == accessToken){
            Call<WeixinTokenRes> call = weixinApiService.getToken("client_credential", appId, appSecret);
            WeixinTokenRes weixinTokenRes = call.execute().body();
            assert weixinTokenRes != null;
            accessToken = weixinTokenRes.getAccess_token();
            weixinAccessToken.put(appId, accessToken);
        }

        // 2. 发送模板消息
        Map<String, Map<String, String>> data = new HashMap<>();
        WeixinTemplateMessageVO.put(data, WeixinTemplateMessageVO.TemplateKey.USER, openId);

        WeixinTemplateMessageVO templateMessageDTO = new WeixinTemplateMessageVO(openId, templateId);
        templateMessageDTO.setUrl("https://gaga.plus");
        templateMessageDTO.setData(data);

        Call<Void> call = weixinApiService.sendMessage(accessToken, templateMessageDTO);
        call.execute();
    }

    @Override
    public String checkLogin(String ticket) {
        return openidToken.getIfPresent(ticket);
    }
}
